Simple Singleton
Came across 2 new aspects of Singleton implementation in Java.
The aspects known so far
- Make the constructor of the Singleton class private
- Define a public static factory method that returns the single instance of the class
So the singleton class looks like this
public class Singleton {
private static Singleton instance= null;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public static void main(String[] args) {
Singleton engine = Singleton.getInstance();
}
}
New aspect #1
There still a loop hole. Multiple instances can still be created by sub classing the singleton class and overriding the Object.clone() protected method. To prevent this, override Object.clone() in the singleton class and throw a CloneNotSupportedException.
New aspect #2
In the factory method there may be a concurrency issue in the check for null instance and creation of the first object. To prevent this issue, designate the factory method as synchronized.
Finally the Singleton class looks like this:
public class Singleton {
private static Singleton instance= null;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static void main(String[] args) {
Singleton engine = Singleton.getInstance();
}
}

0 Comments:
Post a Comment
<< Home